package net.csdn.business.discuss.api.service.impl;

import lombok.extern.slf4j.Slf4j;
import net.csdn.business.discuss.api.model.dto.DiscussLikeDTO;
import net.csdn.business.discuss.api.model.dto.TransferCategoryDTO;
import net.csdn.business.discuss.api.service.IDiscussAsyncService;
import net.csdn.business.discuss.api.service.IDiscussCommentService;
import net.csdn.business.discuss.api.service.IDiscussLikeService;
import net.csdn.business.discuss.api.service.IDiscussVoteService;
import net.csdn.business.discuss.common.config.AsyncThreadPoolConfig;
import net.csdn.business.discuss.common.constant.RedisConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @ClassName DiscussAsyncServiceimpl
 * @Description TODO
 * @Author zhangyl
 * @Date 2023/7/24 11:58
 */
@Slf4j
@Service
public class DiscussAsyncServiceimpl implements IDiscussAsyncService {

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    @Lazy
    private DiscussServiceImpl discussService;

    @Autowired
    @Lazy
    private IDiscussCommentService discussCommentService;

    @Autowired
    @Lazy
    private IDiscussVoteService discussVoteService;

    @Autowired
    @Lazy
    private IDiscussLikeService discussLikeService;

    @Override
    @Async(AsyncThreadPoolConfig.ASYNC_EXECUTOR_POOL_NAME)
    public void transferCategory(TransferCategoryDTO params) {
        discussService.transferCategory(params);
        //清除缓存
        String sourceId=params.getSourceId();
        if(StringUtils.isNotBlank(sourceId)){
            StringBuilder cacheName = new StringBuilder(RedisConstants.DISCUSS_LIST_PAGE);
            cacheName.append(sourceId);
            Cache cache=null;
            try{
                cache = cacheManager.getCache(cacheName.toString());
                cache.clear();
            }catch (Exception e){
                log.info("cache evict cache name:{} error: {} !",cacheName.toString(),e.getMessage());
            }
        }
    }

    @Override
    @Async(AsyncThreadPoolConfig.ASYNC_EXECUTOR_POOL_NAME)
    public void deleteDiscussRelateByDiscussId(String discussId) {
        discussCommentService.deleteDiscussCommentByDiscussId(discussId);
        discussVoteService.deleteVoteByDiscussId(discussId);
    }

    @Override
    @Async(AsyncThreadPoolConfig.ASYNC_EXECUTOR_POOL_NAME)
    public void like(DiscussLikeDTO params) {
        discussLikeService.like(params);
    }

    @Override
    @Async(AsyncThreadPoolConfig.ASYNC_EXECUTOR_POOL_NAME)
    public void unLike(DiscussLikeDTO params) {
        discussLikeService.unLike(params);
    }
}
